package Coriander::Debug;
use strict;
use warnings;
use Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(DEBUG DEBUGSTART DEBUGDONE);

sub DEBUG; sub DEBUGSTART; sub DEBUGDONE;

# This is just a simple module to spit out debug information.
# If properly used, the debug subroutines will visualize how deep you are
# into subroutines.
# 
# use Coriander::Debug;         # Imports DEBUG, DEBUGSTART, and DEBUGDONE.
#
# Coriander::Debug::DEBUGOFF;   # Disable debugging messages
# Coriander::Debug::DEBUGON;    # Enable them again
#
# DEBUGSTART $msg;              # Spit out a debug message and go one level deeper
# DEBUG $msg;                   # Spit out a debug message at the current level
# DEBUGDONE $msg;               # Spit out a debug message and go back one level
# Don't \n-terminate $msg - DEBUG will do that for you.   


our $DEBUG = 1;

sub DEBUGON {
    $DEBUG = 1;
}

sub DEBUGOFF {
    $DEBUG = 0;
}

our $DBGLVL = 0;
our $DBGNEWLINE = 0;
our $DBGBRANCH = "\xC3";
sub DEBUG {
    return unless $DEBUG;
    my $spc = "";
    my $lvl = @_ ? $DBGLVL-1 : $DBGLVL;
    $spc = " \xB3  " x $lvl . (@_ ? " ${DBGBRANCH}\xC4 " : "") if $DBGLVL;
    my $line = $spc . join("", @_);
    while (length($line) > 78) {
        if (length($spc) < 50) {
            print substr($line,0,78), "\n";
            $line = (" \xB3  " x $DBGLVL) . " " . substr($line,78);
        } else {
            $line = substr($line,0,75) . "..."
        }
    }
        
    print "$line\n" if 1;
}

sub DEBUGSTART {
    print "\n" if $DBGLVL == 0;
    DEBUG if $DBGNEWLINE > 1;
    DEBUG @_;
    $DBGLVL++;
    $DBGNEWLINE = $DBGLVL;
}

sub DEBUGDONE {
    local $DBGBRANCH = "\xC0";
    DEBUG @_;
    $DBGLVL--;
    $DBGLVL = $DBGLVL < 0 ? 0 : $DBGLVL;
    DEBUG if $DBGNEWLINE > 1;
    $DBGNEWLINE--;
}

1;


